package Model;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.json.*;

/**
 * Servlet implementation class RegistrationServlet
 */
@WebServlet("/registration")
public class RegistrationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Properties props = new Properties();

	@Override
	public void init() {
		InputStream in = this.getServletContext().getResourceAsStream(
				"/config.properties");
		try {
			props.load(in);
		} catch (Exception e) {
			System.err.println("Unrecoverable error. Could not load configuration.");
			return;
		}
	}

	
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("name");
		String email = request.getParameter("email");
		String password1 = request.getParameter("password1");
		String password2 = request.getParameter("password2");
		String registrationStatus;

		
		request.setAttribute("tryingAgain", false);
		RequestDispatcher dispatcher;

		String referer = request.getHeader("Referer");
		System.out.println(referer);
		
		
		int valid = AccountManager.addUser(name, email, password1, password2);

		if (valid >= 0) {
			
			registrationStatus = "Registration Successful";
			referer = "http://localhost:8080/UBCDatingServer/questionnaire.jsp";
			HttpSession session = request.getSession();
			session.setAttribute("registrationStatus", registrationStatus);
			session.setAttribute("loggedIn", true);
			session.setAttribute("userID", valid);

			User myU = new User(valid);
			JSONObject myJson = new JSONObject(myU);
			System.out.print(myJson);
			session.setAttribute("userInfo", myJson);
			session.setAttribute("name", myU.getName());

				// response.sendRedirect(referer);
				String originalTarget = (String) session
						.getAttribute("originalTarget");
				if (originalTarget != null) {

					response.sendRedirect(originalTarget);
					return;
				}
			// dispatcher = request.getRequestDispatcher(referer);
			response.sendRedirect(referer);

		} else {
			referer = "http://localhost:8080/UBCDatingServer/register.jsp";
			registrationStatus = "Registration Failure";
			HttpSession session = request.getSession();
			session.setAttribute("registrationStatus", registrationStatus);
			request.setAttribute("tryingAgain", true);
			// dispatcher = request.getRequestDispatcher(referer);
			response.sendRedirect(referer);
		}
	}

}
